package com.hyl.icon.utils;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import org.springframework.web.multipart.MultipartFile;

public class ExecuteUtils {

    public static BufferedImage compileAndRun(String code, MultipartFile backgroundFile, MultipartFile logoFile, String brandName, String phone, String address) throws Exception {
        // 1. 定义类名
        String className = "DynamicTemplateClass";
        String javaFileName = className + ".java";
        String classFileName = className + ".class";
        String classPath = System.getProperty("java.io.tmpdir");

        // 定义 Java 文件和编译后生成的 class 文件
        File javaFile = new File(classPath, javaFileName);
        File classFile = new File(classPath, classFileName);

        try {
            // 2. 将 Java 代码写入临时文件
            try (FileWriter writer = new FileWriter(javaFile)) {
                writer.write(code);
            }

            // 3. 编译 Java 代码
            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            int result = compiler.run(null, null, null, javaFile.getAbsolutePath());
            if (result != 0) {
                throw new RuntimeException("代码编译失败");
            }

            // 4. 加载编译后的类
            URLClassLoader classLoader = URLClassLoader.newInstance(new URL[]{new File(classPath).toURI().toURL()});
            Class<?> clazz = Class.forName(className, true, classLoader);
            Object instance = clazz.getDeclaredConstructor().newInstance();

            // 5. 通过反射调用 generateBrandImage 方法
            Method method = clazz.getMethod("generateBrandImage", MultipartFile.class, MultipartFile.class, String.class, String.class, String.class);
            return (BufferedImage) method.invoke(instance, backgroundFile, logoFile, brandName, phone, address);
        } finally {
            // 6. 清理临时文件
            if (javaFile.exists()) {
                javaFile.delete();
            }
            if (classFile.exists()) {
                classFile.delete();
            }
        }
    }
}
